package service

import (
	"errors"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
	"gin-vue-admin/utils"

	"gorm.io/gorm"
)

// 用户注册
func Register(u model.SysUser) (userInter model.SysUser, err error) {
	var user model.SysUser
	if !errors.Is(global.GVA_DB.Where("username = ?", u.UserName).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
		return userInter, errors.New("用户名已注册")
	}
	// 否则 附加uuid 密码md5简单加密 注册
	u.Password = utils.MD5V([]byte(u.Password))
	//u.UUID = uuid.NewV4()
	err = global.GVA_DB.Create(&u).Error
	return u, err
}

// 用户登录
func Login(u *model.SysUser) (userInter *model.SysUser, err error) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = global.GVA_DB.Table("sys_user").
		Where("sys_user.user_name = ? AND sys_user.password = ?", u.UserName, u.Password).
		Joins("left join sys_user_role on sys_user_role.user_id = sys_user.user_id").Scan(&user).Error
	return &user, err
}

// 修改用户密码
func ChangePassword(u *model.SysUser, newPassword string) (userInter *model.SysUser, err error) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = global.GVA_DB.Where("username = ? AND password = ?", u.UserName, u.Password).First(&user).Update("password", utils.MD5V([]byte(newPassword))).Error
	return u, err
}

// 分页获取数据
func GetUserInfoList(info request.QueryUser) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.SysUser{})
	var userList []model.SysUser
	if info.UserName != "" {
		db = db.Where("`user_name` LIKE ?", "%"+info.UserName+"%")
	}
	if info.Status != "" {
		db = db.Where("`status` = ?", info.Status)
	}
	if info.PhoneNumber != "" {
		db = db.Where("`phonenumber` LIKE ?", "%"+info.PhoneNumber+"%")
	}
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&userList).Error
	return userList, total, err
}

// 设置一个用户的权限
func SetUserAuthority(userId int, authorityId string) (err error) {
	err = global.GVA_DB.Where("uuid = ?", userId).First(&model.SysUser{}).Update("authority_id", authorityId).Error
	return err
}

// 删除用户
func DeleteUser(id float64) (err error) {
	var user model.SysUser
	err = global.GVA_DB.Where("id = ?", id).Delete(&user).Error
	return err
}

//  设置用户信息
func SetUserInfo(reqUser model.SysUser) (user model.SysUser, err error) {
	err = global.GVA_DB.Updates(&reqUser).Error
	return reqUser, err
}

// 通过id获取用户信息
func FindUserById(id int) (user *model.SysUser, err error) {
	var u model.SysUser
	err = global.GVA_DB.Where("`id` = ?", id).First(&u).Error
	return &u, err
}

// 通过uuid获取用户信息
func FindUserByUuid(uuid string) (user *model.SysUser, err error) {
	var u model.SysUser
	if err = global.GVA_DB.Where("`uuid` = ?", uuid).First(&u).Error; err != nil {
		return &u, errors.New("用户不存在")
	}
	return &u, nil
}
